package com.piece.admin.service;

import com.piece.admin.model.TbSmsChannel;
import com.piece.admin.repository.TbSmsChannelRepository;
import com.piece.core.framework.util.collection.CollectionUtil;
import com.piece.core.framework.util.object.BeanUtil;
import com.piece.core.jpa.repository.BaseService;
import com.piece.core.message.client.SmsClientFactory;
import com.piece.core.message.enums.SmsChannelType;
import com.piece.core.message.properties.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Slf4j
@Service
@Transactional
public class TbSmsChannelService extends BaseService<TbSmsChannel, String> {

    @Resource
    private TbSmsChannelRepository tbSmsChannelRepository;

    @Resource
    private SmsClientFactory smsClientFactory;

    @PostConstruct
    public void initRepository() {
        setRepository(tbSmsChannelRepository);

        // 初始化短信客户端工厂
        if (null != smsClientFactory) {
            List<TbSmsChannel> clients = tbSmsChannelRepository.findAll();
            if (CollectionUtil.isNotEmpty(clients)) {
                clients.stream().forEach(client -> {
                    updateSmsClientProperties(client);
                });
            }
        }
    }

    @Override
    public TbSmsChannel insertOrUpdate(TbSmsChannel channel) throws Exception {
        if (null == channel.getAppId()) {
            channel = tbSmsChannelRepository.insert(channel);
        } else {
            tbSmsChannelRepository.update(channel);
        }

        updateSmsClientProperties(channel);
        return channel;
    }

    private void updateSmsClientProperties(TbSmsChannel channel) {
        SmsProperties properties = new SmsProperties();
        try {
            BeanUtil.copyProperties(channel, properties);
            smsClientFactory.createOrUpdateClient(properties);
        } catch (Exception e) {
            log.error("更新短信渠道[{}]异常：{}", channel.getCode(), e);
        }
    }

    @Override
    public void delete(Serializable id) throws Exception {
        TbSmsChannel channel = findById(id);
        if (null != channel) {
            super.delete(id);
            smsClientFactory.removeClient(SmsChannelType.getByCode(channel.getCode()));
        }
    }

    @Override
    public int delete(Serializable[] ids) throws Exception {
        for (Serializable id : ids) {
            delete(id);
        }
        return ids.length;
    }
}
